#include <string.h>
#include <string>
#include <stdlib.h>
#include "NWNXPlanner.h"


CNWNXPlanner::CNWNXPlanner()
{
    confKey = "PLANNER";
    
}

CNWNXPlanner::~CNWNXPlanner()
{
    
}

bool CNWNXPlanner::OnCreate(gline *config, const char *LogDir)
{
	char log[128];
	sprintf (log, "%s/nwnx_planner.txt", LogDir);

	// call the base class function
	if (!CNWNXBase::OnCreate(config,log))
		return false;
	Log(0,"NWNX Planner V.0.0.1\n");
	Log(0,"(c) 2012 by the Mahmud Hasan\n");
	Log(0,"RMIT University, Melbourne, Australia.\n");
	Log(0,"Based on the Win32 version (c) 2003 by Ingmar Stieger (Papillon)\n");
        
        _mng = new NWNXManager();
        _mng->loadPDDL();
        _mng->buildPlan();

	return true;
}


bool CNWNXPlanner::OnRealease()
{
    delete _mng;
    return CNWNXBase::OnRelease();
}

char* CNWNXPlanner::OnRequest(char* gameObject, char* request, char* parameters)
{
    this->pGameObject = gameObject+4;

	Log(2,"(S) Request: \"%s\"\n",request);
	Log(3,"(S) Params:  \"%s\"\n",parameters);

	if (strncmp(request, "GETACTION", 9) == 0)
	{
                GetAction(parameters);
	}else if(strncmp(request, "SETACTION", 9) == 0){
                TestPlanner(parameters);
	}

    return NULL;
}

/*
unsigned long CNWNXPlanner::OnRequestObject (char *gameObject, char* Request)
{

	return OBJECT_INVALID;
}
*/

void CNWNXPlanner::TestPlanner(char* value)
{
    char strMessage[100];
    strcpy(strMessage, value);
    strcat(strMessage, "\n");
    Log(0, strMessage);
}


void CNWNXPlanner::GetAction(char* value)
{
    
    int length = strlen(value);
    std::cout<<"Length: "<<length<<std::endl;
    
    std::string msg = _mng->getNextAction();
    int msgLength = msg.length();
    std::cout<<"Msg Length: "<<msgLength<<std::endl;
    if(msgLength<length){
        strncpy(value, msg.c_str(), msgLength);
	*(value+msgLength) = 0x0;
    }else{
        strncpy(value, msg.c_str(), length);
	*(value+length) = 0x0;
    }
    
    Log(0, value);
}
